package com.medic.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * http请求帮助类
 * @author Mr.zhang
 *
 */
public class HttpUtil {

	/**
	 * get方式请求
	 * 
	 * @param url
	 *            请求地址
	 * @return 字符串
	 */
	public static String getReq(String url) {
		String resJson = "";
		String line = "";
		URL openUrl = null;
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		InputStreamReader input = null;
		InputStream is = null;
		try {
			openUrl = new URL(url);
			conn = (HttpURLConnection) openUrl.openConnection();
			conn.connect();
			is = conn.getInputStream();
			input = new InputStreamReader(is, CacheUtil.getConfig().getProperty(StringUtil.ENCODE));
			reader = new BufferedReader(input);
			while ((line = reader.readLine()) != null) {
				resJson = resJson + line;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (input != null) {
					input.close();
				}
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e) {

			}
		}
		return resJson;
	}

	/**
	 * post方式请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            参数map集合
	 * @return 字符串
	 */
	public static String postReq(String url, Map<String, String> params) {
		String resJson = "";
		String line = "";
		URL openUrl = null;
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		InputStreamReader input = null;
		InputStream is = null;
		OutputStream os = null;
		OutputStreamWriter writer = null;
		try {
			openUrl = new URL(url);
			conn = (HttpURLConnection) openUrl.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.connect();
			os = conn.getOutputStream();
			writer = new OutputStreamWriter(os);
			// 参数转化
			writer.write(getParams(params));
			writer.flush();
			// 读取返回参数
			is = conn.getInputStream();
			input = new InputStreamReader(is, CacheUtil.getConfig().getProperty(StringUtil.ENCODE));
			reader = new BufferedReader(input);
			while ((line = reader.readLine()) != null) {
				resJson = resJson + line;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (input != null) {
					input.close();
				}
				if (reader != null) {
					reader.close();
				}
				if (os != null) {
					os.close();
				}
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e) {

			}
		}
		return resJson;
	}

	/**
	 * 下载网络上的文件
	 * 
	 * @param url
	 *            请求地址
	 * @param path
	 *            文件存储路径
	 * @param fileName
	 *            文件的名字（不包括后缀名）
	 * @return 保存成功的文件名
	 */
	public static String getReq(String url, String path, String fileName) {
		String result = "";
		URL openUrl = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		OutputStream os = null;
		byte[] bs = new byte[1024];
		int len;
		File destFile = null;
		String contentType = "";
		try {
			openUrl = new URL(url);
			conn = (HttpURLConnection) openUrl.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();
			contentType = conn.getContentType();
			contentType = contentType.substring(contentType.lastIndexOf("/") + 1);
			// 判断是否是可上传文件
			if (StringUtil.filterFileType(contentType)) {
				if (fileName.contains(".")) {
					fileName = fileName.substring(0, fileName.indexOf("."));
				}
				fileName = fileName + "." + contentType;
				destFile = new File(path, fileName);
				if (destFile.getParentFile() != null && !destFile.getParentFile().exists()) {
					destFile.getParentFile().mkdirs();
				}
				is = conn.getInputStream();
				os = new FileOutputStream(destFile.getAbsolutePath());
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				result = destFile.getName();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * 遍历参数map，并转换成post请求需要的数据
	 * 
	 * @param params
	 *            参数map集合
	 * @return 返回数据
	 * @throws UnsupportedEncodingException
	 */
	public static String getParams(Map<String, String> params) throws UnsupportedEncodingException {
		String paramsStr = "";
		for (Map.Entry<String, String> entry : params.entrySet()) {
			paramsStr = paramsStr + "&" + entry.getKey() + "="
					+ URLEncoder.encode(entry.getValue(), CacheUtil.getConfig().getProperty(StringUtil.ENCODE));
		}
		paramsStr = paramsStr.substring(1);
		return paramsStr;
	}
}
